package com.example.demo.controller;

import com.example.demo.common.VerifyImageUtil;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@RestController
public class TestController {
    @GetMapping("init")
    public Map init(HttpSession session) throws IOException {
        Map map = new HashMap();
        List<byte[]> imgList = new ArrayList<byte[]>();
        List<byte[]> tpllist = new ArrayList<byte[]>();
        VerifyImageUtil.initValidateResources(imgList, tpllist);

        byte[] targetIS = null;
        byte[] templateIS = null;
        Random ra = new Random();
        if (null != imgList) {
            int rd = ra.nextInt(imgList.size());
            targetIS = imgList.get(rd);
        }
        if (null != tpllist) {
            int rd = ra.nextInt(tpllist.size());
            templateIS = tpllist.get(rd);
        }
        Map<String, Object> pictureMap = null;
        try {
            pictureMap = VerifyImageUtil.pictureTemplatesCut(templateIS, targetIS, "png", "jpg");
            String newImage = Base64Utils.encodeToString((byte[]) pictureMap.get("newImage"));
            String sourceImage = Base64Utils.encodeToString((byte[]) pictureMap.get("oriCopyImage"));
            int X = (int) pictureMap.get("X");
            int Y = (int) pictureMap.get("Y");
            map.put("Y",Y);
            map.put("newImage", newImage);
            map.put("sourceImage", sourceImage);
            session.setAttribute("X", X);
        } catch (Exception e) {

        }
        return map;
    }

    /**
     * 验证方法 (有验证码的方法提交，有时候也可以带上验证参数，做后端二次验证)
     *
     * @return
     */
    @GetMapping(value = "check")
    public boolean check(HttpSession session, int X) {
        Integer x = (Integer) session.getAttribute("X");
        if (x == null) return false;
        if (Math.abs(x - X) > 5) {
            return false;
        } else {
            return true;
        }
    }
}
